<?php
namespace control;
/*
*工序报工统计类
*/

class processReportStatisticsClass extends adIndexClass
{
    private const page = 'processReportStatistics';
    private const title = '工序报工统计';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'reportNo'          => [
                        'name'  => "工序报工单",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '源单编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'orderType'  => [
                        'name'  => '单据类型',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '派工数量',
                        'width' => 120,
                    ],
                    'preReportNum'          => [
                        'name'  => '上工序报工合格数量',
                        'width' => 150,
                    ],
                    'passNum'          => [
                        'name'  => '本工序报工合格数量',
                        'width' => 150,
                    ],
                    'notReportNum'          => [
                        'name'  => '未报工数量',
                        'width' => 120,
                    ],
                    'badNum'          => [
                        'name'  => '不合格数量',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "源单编号"   => text(array("name" => "orderNo")),
                    "单据类型"   => select(array("name" => "orderType", 'option'=>['生产计划'=>'生产计划单','半成品'=>'半成品加工单'])),
                    "产品编码" => text(array("name" => "code")),
                ],
                [
                    "产品名称" => text(array("name" => "materialName")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组machiningOrder
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "b.orderType" => $this->post('orderType'),
            "b.coid"=>self::$coid,
            "b.state"=>'已确认',
            "a.state"=>'已确认'
        );
        $and = '';
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.orderNo desc,a.orderNo',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "process_report as a join machining_order as b on a.machiningOrderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,a.orderNo as reportNo,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.orderType,b.recordDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            if ($array['sourceTable'] =='machining_card_detail'){
                //生产流转卡
                $machining_card_detail = query('machining_card_detail', "id = '$array[sendId]'");
                $sourceOrder =query('machining_card', "id = '$machining_card_detail[orderId]'");
                $preCardDetail = query('machining_card_detail',"orderId = '$machining_card_detail[orderId]' and list < $machining_card_detail[list] order by list desc");
            }else{
                //派工单
                $sourceOrder = query('machining_send_order', "id = '$array[sendId]'");
                $routingDetail = query('routing_detail', "id = '$sourceOrder[routingMxId]'");
                $preRoutingDetail = query('routing_detail',"orderId = '$routingDetail[orderId]' and list < '$routingDetail[list]' order by list desc");
                $preCardDetail = query('machining_send_order',"routingMxId = '$preRoutingDetail[id]' and machiningOrderMxId = '".($sourceOrder['machiningOrderMxId']??'')."'");
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'orderType':
                        $row[] = $this->orderType($array['orderType']);
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['orderNum'],'numPrecision');
                        break;
                    case 'preReportNum':
                        //上工序报工数量
                        $preReportNum = find(array('table' => 'process_report', 'single' => "sendId = '$preCardDetail[id]' and state = '已确认'", 'field' => "ifnull(sum(yield-badNum),0) as total"))['total'];
                        $preReportNum = self::lostZero($preReportNum,'numPrecision');
                        $row[] = $preReportNum;
                        break;
                    case 'passNum':
                        $row[] = self::lostZero($array['yield']-$array['badNum'],'numPrecision');
                        break;
                    case 'notReportNum':
                        //已报工数量
                        $reportNum = find(array('table' => 'process_report', 'single' => "sendId = '$array[sendId]'  and orderNo <='$array[reportNo]' and state = '已确认'", 'field' => "ifnull(sum(yield-badNum),0) as total"))['total'];
                        $row[] = self::lostZero(machiningOrderClass::notLessThanZero($sourceOrder['num']-$reportNum),'numPrecision');
                        break;
                    case 'badNum':
                        //不合格数量
                        $badNum = find(array('table' => 'process_report', 'where' => "sendId = '$array[sendId]' and state = '已确认", 'sum' => "badNum"));
                        $badNum = self::lostZero($badNum,'numPrecision');
                        $row[] = $badNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "process_report as a join machining_order as b on a.machiningOrderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.orderNum),0) as num,ifnull(sum(a.yield-a.badNum),0) as passNum",
        ]);
        $badNum = find(array('table' => 'process_report', 'where' => "sendId in (select a.sendId from process_report as a join machining_order as b on a.machiningOrderId = b.id join material as c on c.id = a.materialId where 1=1 {$where}) and state = '已确认", 'sum' => "badNum"));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'passNum'        => self::lostZero($totalQuery['passNum'], 'numPrecision'),
            'badNum'        => self::lostZero($badNum, 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function orderType($type): string
    {
        return match ($type){
            '生产计划'=>'生产计划单',
            '半成品'=>'半成品加工单',
            default=>'',
        };
    }
    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "process_report as a join machining_order as b on a.machiningOrderId = b.id join material as c on c.id = a.materialId",
                    'field'=>"a.*,a.orderNo as reportNo,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.orderType,b.recordDate",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by b.orderNo desc,a.orderNo",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $process = query('process',"id = '$array[processId]'");
                if ($array['sourceTable'] =='machining_card_detail'){
                    //生产流转卡
                    $machining_card_detail = query('machining_card_detail', "id = '$array[sendId]'");
                    $sourceOrder =query('machining_card', "id = '$machining_card_detail[orderId]'");
                    $preCardDetail = query('machining_card_detail',"orderId = '$machining_card_detail[orderId]' and list < $machining_card_detail[list] order by list desc");
                }else{
                    //派工单
                    $sourceOrder = query('machining_send_order', "id = '$array[sendId]'");
                    $routingDetail = query('routing_detail', "id = '$sourceOrder[routingMxId]'");
                    $preRoutingDetail = query('routing_detail',"orderId = '$routingDetail[orderId]' and list < $routingDetail[list] order by list desc");
                    $preCardDetail = query('machining_send_order',"routingMxId = '$preRoutingDetail[id]' and machiningOrderMxId = '$sourceOrder[machiningOrderMxId]'");
                }
                //上工序报工数量
                $preReportNum = find(array('table' => 'process_report', 'single' => "sendId = '$preCardDetail[id]' and state = '已确认'", 'field' => "ifnull(sum(yield-badNum),0) as total"))['total'];
                $preReportNum = self::lostZero($preReportNum,'numPrecision');
                //已报工数量
                $reportNum = find(array('table' => 'process_report', 'single' => "sendId = '$array[sendId]'  and orderNo <='$array[reportNo]' and state = '已确认'", 'field' => "ifnull(sum(yield-badNum),0) as total"))['total'];
                //不合格数量
                $badNum = find(array('table' => 'process_report', 'where' => "sendId = '$array[sendId]' and state = '已确认", 'sum' => "badNum"));
                $badNum = self::lostZero($badNum,'numPrecision');
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '工序报工单'=>$array['reportNo'],
                            '源单编号'=>$array['orderNo'],
                            '单据类型'=>$this->orderType($array['orderType']),
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '工序'=>$process['name'],
                            '派工数量'=> self::lostZero($sourceOrder['num'],'numPrecision'),
                            '上工序报工合格数量'=>$preReportNum,
                            '本工序报工合格数量'=>self::lostZero($array['yield']-$array['badNum'],'numPrecision'),
                            '未报工数量'=> self::lostZero($sourceOrder['num']-$reportNum,'numPrecision'),
                            '不合格数量'=>$badNum,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了工序报工统计表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "工序报工统计表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'工序报工单',
                    'aliasName'=>'工序报工单',
                ],
                [
                    'columnName'=>'源单编号',
                    'aliasName'=>'源单编号',
                ],
                [
                    'columnName'=>'单据类型',
                    'aliasName'=>'单据类型',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'派工数量',
                    'aliasName'=>'派工数量',
                ],
                [
                    'columnName'=>'上工序报工合格数量',
                    'aliasName'=>'上工序报工合格数量',
                ],
                [
                    'columnName'=>'本工序报工合格数量',
                    'aliasName'=>'本工序报工合格数量',
                ],
                [
                    'columnName'=>'未报工数量',
                    'aliasName'=>'未报工数量',
                ],
                [
                    'columnName'=>'不合格数量',
                    'aliasName'=>'不合格数量',
                ],
            ]
        };
    }
}

